package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 霍森彪
 * @date 2022/7/28 13:36
 */
@Slf4j
@Service
public class ApUnlikesBehaviorServiceImpl implements ApUnlikesBehaviorService {

    @Autowired
    private CacheService cacheService;
    /**
     * 文章喜欢和不喜欢
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unlike(UnLikesBehaviorDto dto) {
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        Integer userId = user.getId();
        Short type = dto.getType();
        //不喜欢逻辑
        if (type == 0){
            //去重
            cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR+dto.getArticleId(),userId.toString());
            //向不喜欢记录哈希结构添加一条记录
            Long currentTimeMillis = System.currentTimeMillis();
            cacheService.hPut(BehaviorConstants.UN_LIKE_BEHAVIOR+dto.getArticleId(),userId.toString(),currentTimeMillis.toString());
        }else{
            //取消不喜欢逻辑
            cacheService.hDelete(BehaviorConstants.UN_LIKE_BEHAVIOR+dto.getArticleId(),userId.toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
